package com.wunong.smart.bigdata.jdk;

import java.util.concurrent.RecursiveTask;

/**
 * 求数组 start -> end 区间的和
 *
 * @author created by zealot.zt
 */
public class SumArrayForkJoinTask extends RecursiveTask<Integer> {

    private final int[] values;
    private final int start;
    private final int end;
    private final int threshold = 2;

    public SumArrayForkJoinTask(int[] values, int start, int end) {
        this.values = values;
        this.start = start;
        this.end = end;
    }

    public SumArrayForkJoinTask(int[] values) {
        this.values = values;
        this.start = 0;
        this.end = values.length - 1;
    }

    @Override
    protected Integer compute() {
        boolean canComplete = end - start <= threshold;
        if (canComplete) {
            return this.sum();
        }

        int mid = (start + end) / 2;

        SumArrayForkJoinTask leftTask = new SumArrayForkJoinTask(values, start, mid);
        System.out.printf("split tasks from [%s, %s]%n", start, mid);

        SumArrayForkJoinTask rightTask = new SumArrayForkJoinTask(values, mid + 1, end);
        System.out.printf("split tasks from [%s, %s]%n", mid + 1, end);

        // 调用fork方法：执行子任务
        leftTask.fork();
        rightTask.fork();

        // 调用join方法：合并子任务结果
        return leftTask.join() + rightTask.join();
    }

    /**
     * 求和数据
     *
     * @return
     */
    public int sum() {
        int sum = 0;
        for (int i = start; i <= end; i++) {
            sum += values[i];
        }
        return sum;
    }

}